package yns.springboot.guide.demo.controller.data.rabbitmq;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.AMQP.BasicProperties;

import yns.springboot.guide.demo.configure.data.rabbitmq.RabbitmqConfigure;
import yns.springboot.guide.demo.data.consumer.rabbitmq.driver.RabbitmqDriverConsumer;

@RestController
@RequestMapping("/rabbitmq/driver")
public class TestRabbitmqDriverController {
	
	// http://localhost:8080/rabbitmq/driver/producer
	// http://localhost:8080/rabbitmq/driver/consumer
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private Channel channel;
	
	@Autowired
	private RabbitmqConfigure rabbitmqConfigure;
	
	@GetMapping("/producer")
	public String producerRabbitmq() throws IOException {
		
		String queue = rabbitmqConfigure.getQueue();
		String exchange = rabbitmqConfigure.getExchange();
		String routingKey = rabbitmqConfigure.getRoutingKey();
		
		HashMap<String,Object> headers = new HashMap<>();
		headers.put("TestRabbitmqDriverController", "producerRabbitmq");
		
		BasicProperties basicProperties = new BasicProperties.Builder()
				.userId("user")
				.headers(headers)
				.contentType("text/plan")
				.priority(1)
				.build();;
		
		String message = LocalDateTime.now().toString();
		
		logger.info("producerRabbitmq  queue : " + queue);
		logger.info("producerRabbitmq  exchange : " + exchange);
		logger.info("producerRabbitmq  routingKey : " + routingKey);
		logger.info("producerRabbitmq  basicProperties : " + basicProperties.toString());
		logger.info("producerRabbitmq  message : " + message);
		
		channel.basicPublish(exchange, routingKey, basicProperties, message.getBytes("UTF-8"));

		return "test.rabbitmq.driver.producer";
	}
	
	@GetMapping("/consumer")
	public String consumerRabbitmq() throws IOException {
		
		String queue = rabbitmqConfigure.getQueue();
		String exchange = rabbitmqConfigure.getExchange();
		String routingKey = rabbitmqConfigure.getRoutingKey();
		
		logger.info("consumerRabbitmq  queue : " + queue);
		logger.info("consumerRabbitmq  exchange : " + exchange);
		logger.info("consumerRabbitmq  routingKey : " + routingKey);

		RabbitmqDriverConsumer rabbitmqDriverConsumer = new RabbitmqDriverConsumer(channel);
		channel.basicConsume(queue, true, rabbitmqDriverConsumer);

		return "test.rabbitmq.driver.consumer";
	}

}
